/**  *   */
package search;
import interfaces.SearchDataBase;

import java.util.LinkedList;
import java.util.Queue;

import logger.ForumLogger;

import persistence.XMLUtils;
import search.items.SearchQueueItem;
import search.items.UpdatePostQueueItem;
import search.items.deletedPostQueueItem;
import search.items.newPostQueueItem;
import domain.items.Post;

/**  * @author Administrator  *  */
public class SearchDataUpdatorImp implements Runnable {
	///////////// SHAI ///////////////
	private final int TimeInterval = 10;
	/////////////////////////////////

	private SearchDataBase _searchDB;
	public static Queue<SearchQueueItem> mySearchQueue = new LinkedList<SearchQueueItem>();

	public SearchDataUpdatorImp(SearchDataBase searchDB){
		this._searchDB = searchDB;
	}


	public void run() {
		 // Here is the Check part
        while (true) {
        	while(!mySearchQueue.isEmpty()){
        		itemTreatment(mySearchQueue.remove());
        	}
        	try {
        		//TODO : maybe better move this call into the end of the 'itemTreatment' method
        		XMLUtils.saveDB(this._searchDB, SearchDBManager.FILE_NAME);
        	}
        	catch (Exception e) {
        		System.err.println("error while writing search Data Base");
        	}
        	//////////////////////////////////////////////////
        		try {
                    // Here is the Wait part
                     Thread.sleep(this.TimeInterval);
        			//Thread.sleep(60 * 10);
                } catch (InterruptedException e) {}
        }

	}

	private void itemTreatment(SearchQueueItem item){
		//////////////// SHAI /////////////////
		//System.err.println("removing item from searchEngine Queue");
		ForumLogger.logGeneral("removing item from searchEngine Queue");
		/////////////////////////////////////////
		if (item instanceof newPostQueueItem){
			newPostTreatment(item.getPost());
			}
		if (item instanceof deletedPostQueueItem){
			System.out.println("handle deleted post in search");
			deletePostTreatment(item.getPost());
			}
		if (item instanceof UpdatePostQueueItem){
			String tOldTitle= ((UpdatePostQueueItem)item).getOldTitle();
			String tOldContent= ((UpdatePostQueueItem)item).getOldContent();
			deletePostTreatment(item.getPost(), tOldTitle, tOldContent);
			newPostTreatment(item.getPost());
			}
		}
	public void newPostTreatment(Post post){
		// ayal
		//this._searchDB.addUserPost( ((Member)(post.getOwner())).getUserName() , post);
		//inserting the title of the post to the DB
		addNewPostToSearchDataBase(post, post.getName());
		//inserting the content of the post to the DB
		addNewPostToSearchDataBase(post, post.getText());
		}
	public void deletePostTreatment(Post post, String title ,String content){
		this._searchDB.removeUserPost( post.getOwner() , post);
		//remove the title of the post to the DB
		removePostFromDataBase(post, title);
		//remove the content of the post to the DB
		removePostFromDataBase(post, content);
		}
	public void deletePostTreatment(Post post){
		this._searchDB.removeUserPost( post.getOwner() , post);
		//removing the title
		removePostFromDataBase(post, post.getName());
		//removing the content
		removePostFromDataBase(post, post.getText());
		}
	/**
	 * remove punctuation marks and brackets from the beginning and end of the word
	 * @param word
	 *  @return the word without dot/comma in the end
	 * */
	public String removePunctuationMarks (String word){
		while (word.startsWith("(")){
			word = word.substring(1);
			}
		while (word.endsWith(".") | word.endsWith(",") | word.endsWith("?") | word.endsWith("!")
				| word.endsWith(")") | word.endsWith("\"") | word.endsWith(":") | word.endsWith("'")
				| word.endsWith("-")){
			word = word.substring(0, word.length()-1);
			}
		return word;
		}
	public void addNewPostToSearchDataBase(Post post, String sentence){
		String[] tWords = sentence.split(" ");
		for (int i = 0; i < tWords.length; i++) {
			tWords[i]= removePunctuationMarks(tWords[i]);
			tWords[i]= tWords[i].toLowerCase();
			if ((!tWords[i].equals("")) & (!tWords[i].equals(" "))){
				this._searchDB.addWordReference(tWords[i], post);
				}
			}
		}
	public void removePostFromDataBase(Post post, String sentence){
		String[] tWords = sentence.split(" ");
		for (int i = 0; i < tWords.length; i++) {
			tWords[i]= removePunctuationMarks(tWords[i]);
			tWords[i]= tWords[i].toLowerCase();
			if ((!tWords[i].equals("")) & (!tWords[i].equals(" "))){
				this._searchDB.removeWordReference(tWords[i], post);
				}
			}
		}
}

